package com.longge;

/**
 * @program: my-code
 * @description:
 * @author: longge
 * @create: 2021-02-28 23:24
 */
public class BuildTree1 {

    public TreeNode buildTree(int[] preorder, int[] inorder) {
        if (preorder.length == 0) return null;
        return build(preorder, 0, preorder.length-1, inorder, 0, inorder.length-1);
    }

    private TreeNode build(int[] preorder, int preStart, int preEnd, int[] inorder, int inStart, int inEnd) {

        if (preStart > preEnd) {
            return null;
        }
        int rootVal = preorder[preEnd];
        int index = 0;
        for (int i = inStart; i <= inEnd; i++) {
            if (rootVal == inorder[i]) {
                index = i;
                break;
            }
        }
        TreeNode treeNode = new TreeNode(rootVal);
        int leftSize = index - inStart;
        treeNode.left = build(preorder, preStart, preStart+leftSize-1, inorder,inStart ,index-1 );
        treeNode.right = build(preorder,preStart+leftSize , preEnd-1, inorder,index+1 ,inEnd);
        return treeNode;
    }

    public static void main(String[] args) {
        new BuildTree1().buildTree(new int[]{9,15,7,20,3},new int[]{9,3,15,20,7});

    }
}
